package fr.pchab.androidrtc;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import fr.pchab.androidrtc.bean.UserBean;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * Created by lixl on 2018/10/24.
 * <p>
 * desc:
 */
public class FirstActivity extends Activity{

    private TextView tv_callerId;
    private Button btn_refresh;
    private Button btn_joined;
    private ListView lv;

    private String callerId;
    private ArrayList<String> callerList = new ArrayList<>();
    private List<UserBean> list = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        initView();
        initData();
        getUser();
    }

    private void initView(){
        tv_callerId = (TextView) findViewById(R.id.tv_callerId);
        btn_refresh = (Button) findViewById(R.id.btn_refresh);
        btn_joined = (Button) findViewById(R.id.btn_joined);
        lv = (ListView) findViewById(R.id.lv);
    }

    private void initData(){
        btn_refresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getUser();
            }
        });

        btn_joined.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (callerList.size() > 1){
                    Toast.makeText(FirstActivity.this, callerList.toString(), Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(FirstActivity.this, RtcActivity.class);
                    intent.putExtra("callerId", callerList.toString());
                    startActivity(intent);
                } else {
                    Toast.makeText(FirstActivity.this, "至少2人参加群里聊", Toast.LENGTH_SHORT).show();
                }
            }
        });

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                callerId = list.get(position).getId();
                Intent intent = new Intent(FirstActivity.this, RtcActivity.class);
                intent.putExtra("callerId", callerId);
                startActivity(intent);
            }
        });
    }

    /**
     * 接口请求数据
     */
    private void getUser(){
        String url = "http://" + getResources().getString(R.string.host) +
                ":" + getResources().getString(R.string.port) +
                "/streams.json";
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                //String result = "[{\"name\":\"wkh1\",\"id\":\"mCsW8kx88VrYsRQiAAAP\"},{\"name\":\"wkh1\",\"id\":\"vPRL9Ug56XQGaP0VAAAT\"}]";
                Log.d(TAG, "onResponse: " + result);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        Type lt = new TypeToken <List<UserBean>>() {}.getType();
                        list = (List<UserBean>) gson.fromJson(result, lt);
                        lv.setAdapter(new UserAdapter(FirstActivity.this, list));
                    }
                });

            }
        });

    }

    private class UserAdapter extends BaseAdapter{
        private List<UserBean> list;
        private Context mContext;
        public UserAdapter(Context mContext, List<UserBean> list){
            this.list = list;
            this.mContext = mContext;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_user, null);
                holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
                holder.tv_id = (TextView) convertView.findViewById(R.id.tv_id);
                holder.cb = (CheckBox) convertView.findViewById(R.id.cb);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.tv_name.setText(list.get(position).getName());
            holder.tv_id.setText(list.get(position).getId());
            holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        callerList.add(list.get(position).getId());
                        Toast.makeText(FirstActivity.this, "选中" + list.get(position).getName(), Toast.LENGTH_SHORT).show();
                    }else{
                        callerList.remove(list.get(position).getId());
                        Toast.makeText(FirstActivity.this, "取消选中" + list.get(position).getName(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            return convertView;
        }

        class ViewHolder{
            TextView tv_name;
            TextView tv_id;
            CheckBox cb;
        }
    }
}

